package com.example.forum_system.config;

import com.example.forum_system.common.Result;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @BelongsProject: 0.forum_system
 * @BelongsPackage: com.example.forum_system.config
 * @Author : 游在海里的鱼
 * @CreateTime : 2023-11-03  15:41
 * @Version : 1.0
 * @Description : 统一返回处理
 */
@RestControllerAdvice(basePackages = "com.example.forum_system.controller")
public class ResponseAdvice implements ResponseBodyAdvice {
    ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
         if(body instanceof Result){
             return body;
         }

         if(body instanceof String){
             Result result = Result.success(body);
             try {
                 return objectMapper.writeValueAsString(result);
             } catch (JsonProcessingException e) {
                 e.printStackTrace();
             }
         }
         return Result.success(body);
    }
}
